package com.umerclass.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.lljjcoder.Constant;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.SubscribeMessage;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessView;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessWebview;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umerclass.R;
import com.umerclass.utils.Constants;
import com.umerclass.utils.NetworkUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import okhttp3.Call;
import okhttp3.Request;

/**
 * WXEntryActivity是微信回调的一个类，通常给个透明的主题或者处理完业务逻辑就直接finish。
 * 需要在回调中拿到code，然后再根据code去获取AccessToken，
 * 然后再根据AccessToken和OpenId去获取UserInfo。
 *
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
	private static String TAG = "MicroMsg.WXEntryActivity";

	private String unionid;
	private String openid;

    private IWXAPI api;
    private MyHandler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportActionBar().hide();
        // 隐藏状态栏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		//接收到分享以及登录的intent传递handleIntent方法，处理结果
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
		handler = new MyHandler(this);

		try {
			Intent intent = getIntent();
			api.handleIntent(intent, this);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static class MyHandler extends Handler {
		private final WeakReference<WXEntryActivity> wxEntryActivityWeakReference;

		public MyHandler(WXEntryActivity wxEntryActivity){
			wxEntryActivityWeakReference = new WeakReference<WXEntryActivity>(wxEntryActivity);
		}

		@Override
		public void handleMessage(Message msg) {
			int tag = msg.what;
			switch (tag) {
				case NetworkUtil.GET_TOKEN: {
					Bundle data = msg.getData();
					JSONObject json = null;
					try {
						json = new JSONObject(data.getString("result"));
						String openId, accessToken, refreshToken, scope;
						openId = json.getString("openid");
						accessToken = json.getString("access_token");
						refreshToken = json.getString("refresh_token");
						scope = json.getString("scope");
						/*Intent intent = new Intent(wxEntryActivityWeakReference.get(), SendToWXActivity.class);
						intent.putExtra("openId", openId);
						intent.putExtra("accessToken", accessToken);
						intent.putExtra("refreshToken", refreshToken);
						intent.putExtra("scope", scope);
						wxEntryActivityWeakReference.get().startActivity(intent);*/
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage());
					}
				}
			}
		}
	}
	
	/**
	 *在WXEntryActivity中将接收到的intent及实现了IWXAPIEventHandler接口的
	 * 对象传递给IWXAPI接口的handleIntent方法
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
        api.handleIntent(intent, this);
	}

	/**
	 * 微信发送请求到第三方应用时，会回调到该方法
	 *
	 */

	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
			case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
				goToGetMsg();
				break;
			case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
				goToShowMsg((ShowMessageFromWX.Req) req);
				break;
			default:
				break;
		}
		finish();
	}

	/**
	 * 在onResp中需要实现逻辑，微信返回的数据在这里会被接收。
	 * 微信返回的数据包含code。在onResp需要实现向服务端发送请求，带上code等参数，
	 * 后端再通过相应的参数去请求微信服务端，最终将获取到的用户信息返回给前端Android。
	 */
	@Override
	public void onResp(BaseResp resp) {
		int result = 0;
		Toast.makeText(this, "baseresp.getType = " + resp.getType(), Toast.LENGTH_SHORT).show();
		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			result = R.string.errcode_success;
			String code = ((SendAuth.Resp) resp).code;//需要转换一下才可以
            //获取用户信息
			getAccessToken(code);
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
			result = R.string.errcode_cancel;
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
			result = R.string.errcode_deny;
			break;
		case BaseResp.ErrCode.ERR_UNSUPPORT:
			result = R.string.errcode_unsupported;
			break;
		default:
			result = R.string.errcode_unknown;
			break;
		}
		
		Toast.makeText(this, getString(result) + ", type=" + resp.getType(), Toast.LENGTH_SHORT).show();


		if (resp.getType() == ConstantsAPI.COMMAND_SUBSCRIBE_MESSAGE) {
			SubscribeMessage.Resp subscribeMsgResp = (SubscribeMessage.Resp) resp;
			String text = String.format("openid=%s\ntemplate_id=%s\nscene=%d\naction=%s\nreserved=%s",
					subscribeMsgResp.openId, subscribeMsgResp.templateID, subscribeMsgResp.scene, subscribeMsgResp.action, subscribeMsgResp.reserved);

			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		}

        if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            WXLaunchMiniProgram.Resp launchMiniProgramResp = (WXLaunchMiniProgram.Resp) resp;
            String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s",
                    launchMiniProgramResp.openId, launchMiniProgramResp.extMsg,launchMiniProgramResp.errStr);

            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }

        if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_VIEW) {
            WXOpenBusinessView.Resp launchMiniProgramResp = (WXOpenBusinessView.Resp) resp;
            String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s\nbusinessType=%s",
                    launchMiniProgramResp.openId, launchMiniProgramResp.extMsg,launchMiniProgramResp.errStr,launchMiniProgramResp.businessType);

            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }

        if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_WEBVIEW) {
            WXOpenBusinessWebview.Resp response = (WXOpenBusinessWebview.Resp) resp;
            String text = String.format("businessType=%d\nresultInfo=%s\nret=%d",response.businessType,response.resultInfo,response.errCode);

            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }

		if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
			SendAuth.Resp authResp = (SendAuth.Resp)resp;
			final String code = authResp.code;
			NetworkUtil.sendWxAPI(handler, String.format("https://api.weixin.qq.com/sns/oauth2/access_token?" +
							"appid=%s&secret=%s&code=%s&grant_type=authorization_code", "wxd930ea5d5a258f4f",
					"1d6d1d57a3dd063b36d917bc0b44d964", code), NetworkUtil.GET_TOKEN);
		}
        finish();
	}
	
	private void goToGetMsg() {
	/*	Intent intent = new Intent(this, GetFromWXActivity.class);
		intent.putExtras(getIntent());
		startActivity(intent);
		finish();*/
	}
	
	private void goToShowMsg(ShowMessageFromWX.Req showReq) {
		WXMediaMessage wxMsg = showReq.message;
		WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
		
		StringBuffer msg = new StringBuffer();
		msg.append("description: ");
		msg.append(wxMsg.description);
		msg.append("\n");
		msg.append("extInfo: ");
		msg.append(obj.extInfo);
		msg.append("\n");
		msg.append("filePath: ");
		msg.append(obj.filePath);
		
		/*Intent intent = new Intent(this, ShowFromWXActivity.class);
		intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
		intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
		intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
		startActivity(intent);
		finish();*/
	}

	private void getAccessToken(String code) {
		//获取授权
		StringBuffer loginUrl = new StringBuffer();
		loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
				.append("?appid=")
				.append( Constants.APP_ID)
				.append("&secret=")
				.append(Constants.SECRET)
				.append("&code=")
				.append(code)
				.append("&grant_type=authorization_code");
		OkHttpUtils
				.get()
				.url(loginUrl.toString())
				.build()
				.execute(new StringCallback() {

					@Override
					public void onError(Call call, Exception e, int id) {

					}

					@Override
					public void onResponse(String response, int id) {
						String access = null;
						String openId = null;
						try {
							JSONObject jsonObject = new JSONObject(response);
							access = jsonObject.getString("access_token");
							openId = jsonObject.getString("openid");
							Toast.makeText(WXEntryActivity.this,"access_token:"+ access+ "openId:"+ openId,Toast.LENGTH_LONG);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});



		/*OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
			@Override
			public void onSuccess(String response) {
				String access = null;
				String openId = null;
				try {
					JSONObject jsonObject = new JSONObject(response);
					access = jsonObject.getString("access_token");
					openId = jsonObject.getString("openid");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//获取个人信息
				String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
				OkHttpUtils.ResultCallback<String> reCallback = new OkHttpUtils.ResultCallback<String>() {
					@Override
					public void onSuccess(String responses) {

						String nickName = null;
						String sex = null;
						String city = null;
						String province = null;
						String country = null;
						String headimgurl = null;
						try {
							JSONObject jsonObject = new JSONObject(responses);

							openid = jsonObject.getString("openid");
							nickName = jsonObject.getString("nickname");
							sex = jsonObject.getString("sex");
							city = jsonObject.getString("city");
							province = jsonObject.getString("province");
							country = jsonObject.getString("country");
							headimgurl = jsonObject.getString("headimgurl");
							unionid = jsonObject.getString("unionid");
							loadNetData(1, openid, nickName, sex, province,
									city, country, headimgurl, unionid);

						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(Exception e) {
						Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
						finish();
					}
				};
				OkHttpUtils.get(getUserInfo, reCallback);
			}

			@Override
			public void onFailure(Exception e) {
				Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
				finish();
			}
		};
		OkHttpUtils.get(loginUrl.toString(), resultCallback);*/
	}
}